package com.eic.framework.core.security;

import com.alibaba.fastjson2.JSON;
import com.eic.framework.security.LoginJwtHandler;
import com.ruoyi.common.config.TokenConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface SecurityLoginService {
    Logger logger= LoggerFactory.getLogger(SecurityLoginService.class);
    /**
     * 创建session登录用户
     * @param jwt
     * @return
     */
    public LoginUser createLoginUser(LoginJwtHandler jwt);

    /**
     * @param username
     * @param status
     * @param message
     */
    public void recordLoginInfor(final String username, final String status, final String message);
    /**
     * @param request
     * @return
     */
    public default LoginJwtHandler getRequestJwt(HttpServletRequest request){
        String TOKEN_PREFIX = "Bearer ";
        String token = request.getHeader(TokenConfig.getHeader());
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        if(StringUtils.isBlank(token)){
            return null;
        }
        return LoginJwtHandler.getInstanse(token);
    }

    /**
     * @param resp
     */
    public default void writeUnauthorized(HttpServletResponse resp){
        AjaxResult ajaxResult = AjaxResult.error(HttpStatus.UNAUTHORIZED, MessageUtils.message("user.notfound"));
        ServletUtils.renderString(resp, JSON.toJSONString(ajaxResult));
    }
}
